import axios from 'axios'
import { useRouter } from 'vue-router'
import { PlainMessage } from './index'

const router = useRouter()

const errorMessageDebounce = (() => {
  const errors = new Map()
  const DEBOUNCE_TIME = 3000 // 3秒内不重复显示相同错误

  return message => {
    const now = Date.now()
    const lastTime = errors.get(message)

    if (!lastTime || now - lastTime > DEBOUNCE_TIME) {
      errors.set(message, now)
      PlainMessage.error(message)

      // 自动清理过期的错误记录
      setTimeout(() => {
        errors.delete(message)
      }, DEBOUNCE_TIME)
    }
  }
})()

export const BASE_URL = 'http://127.0.0.1:8080/api'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || BASE_URL,
  timeout: 15000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')

    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },
  error => {
    errorMessageDebounce(`请求错误:' ${error.message || '未知错误'}`)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    // 检查响应类型，如果不是 JSON 则直接返回
    const contentType = response.headers['content-type'] || ''
    if (!contentType.includes('application/json')) {
      return response
    }

    const { data } = response
    if (data.success) {
      return data
    } else {
      errorMessageDebounce(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  },
  error => {
    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 401:
          localStorage.removeItem('token')
          router.push('/login')
          errorMessageDebounce('登录已过期，请重新登录')
          break
        case 403:
          errorMessageDebounce('没有权限访问该资源')
          break
        case 404:
          errorMessageDebounce('请求的资源不存在')
          break
        case 500:
          errorMessageDebounce('服务器错误')
          break
        default:
          errorMessageDebounce(`请求失败: ${data.message}`)
      }
    } else if (error.request) {
      errorMessageDebounce('服务器无响应，请检查网络连接')
    } else {
      error.message !== 'canceled' &&
        errorMessageDebounce(`请求错误: ${error.message}`)
    }

    return Promise.reject(error)
  }
)

export default service
